package orm

import (
	"animal/octopus/common"
	"animal/octopus/model"

	"gorm.io/gorm"

	log "github.com/sirupsen/logrus"
)

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func GetDepList(db *gorm.DB, moduleID uint) ([]model.Dependency, error) {
	var deps []model.Dependency
	result := common.DB(db).Find(&deps, "module_id = ?", moduleID)
	if result.Error != nil {
		log.Error("find dependencies failed")
		return nil, result.Error
	}

	return deps, nil
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func CreateDependency(db *gorm.DB, moduleID uint, depInfo common.DependencyInfo) (uint, error) {
	dependency := model.Dependency{
		Name:       depInfo.Name,
		Desc:       depInfo.Desc,
		Protocol:   depInfo.Protocol,
		TargetType: depInfo.TargetType,
		TargetID:   depInfo.TargetID,
		State:      uint(depInfo.State),
		ModuleID:   moduleID,
	}
	if err := common.DB(db).Create(&dependency).Error; err != nil {
		log.WithField("dep", depInfo).Error("create dependency failed")
		return 0, err
	}

	log.WithField("dep", depInfo).Info("create dependency success")

	return dependency.ID, nil
}

// ------------------------------------------------------------------------------
// TODO: update state only???
// ------------------------------------------------------------------------------
func UpdateDependency(db *gorm.DB, depID uint, dep common.DependencyInfo) error {
	if err := common.DB(db).Model(&model.Dependency{}).Where("id = ?", depID).
		Update("state", uint(dep.State)).Error; err != nil {
		log.WithFields(log.Fields{"dep": depID, "info": dep}).
			Error("update dependency failed")
		return err
	}

	log.WithFields(log.Fields{"dep": depID, "info": dep}).
		Info("update dependency success")

	return nil
}

// ------------------------------------------------------------------------------
//
// ------------------------------------------------------------------------------
func DeleteDependency(db *gorm.DB, depID uint) error {
	if err := common.DB(db).Delete(&model.Dependency{}, depID).Error; err != nil {
		log.WithField("dep", depID).Error("delete dependency failed")
		return err
	}

	log.WithField("dep", depID).Info("delete dependency success")

	return nil
}
